var express = require('express');
var fetch = require('node-fetch');
var router = express.Router();
const userService = require('../service/userService');
const jwt = require("jsonwebtoken");
const {secretKey,sha256} = require('../utils/token');
const APP_ID = 'wx457004f898a98ca0';
const SECRET = 'd8efd912b05ef18ac556cb3e9d1dcd68';
/* GET users listing. */
router.get('/', async function(req, res, next) {
  let data = await userService.findByUsername(req.query.username);
  if(data.length > 0){
    res.send({status:0});
  }else{
    res.send({status:1});
  }
});
router.post('/login',async function(req,res){
  let {username,pwd} = req.body;
  let data = await userService.login(username,sha256(pwd))
  console.log("data",Object.keys(data).length);
  if(Object.keys(data).length > 0){
    // req.session.user = data;
    let authToken = jwt.sign({user:data}, secretKey);
    res.send({token: authToken});
    return;
  }
  res.send(data);
 
});
router.get('/weixinLogin',async function(req,res){
  let code = req.query.code;
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
  let fetchResult = await fetch(url);
  let data = await fetchResult.json();
  console.log('data',url,data)
  if(!data.errcode){
    let user = await userService.findByUsername(data.openid);
    if(Object.keys(user).length > 0){
      res.send(user);
    }else{
      let newUser = await userService.register({username:data.openid,pwd:''});
      res.send(newUser);
    }
  }else{
    res.send({});
  }
});
router.post('/',async function(req,res){
  let {username,pwd} = req.body;

  let data = await userService.register({username,pwd:sha256(pwd)});
  res.send(data);
});

module.exports = router;
